package metadata.schema;

//import static java.sql.Types.*;
import java.util.*;

import represent.type.*;
import utils.Constant;

/**
 * The record schema of a table.
 * A schema contains the name and type of
 * each field of the table, as well as the length
 * of each varchar field.
 * @author Edward Sciore
 *
 */
public class Schema {
	private String tableName;

	private int currentLength = 0;
	private Hashtable<String, Field> fieldTable = new Hashtable<String, Field>();
	private ArrayList<String> fields;
	private ArrayList<String> primaryKeys = new ArrayList<String>();

	/**
	 * Creates an empty schema.
	 * Field information can be added to a schema
	 * via the five addXXX methods. 
	 */
	public Schema(String tableName) {
		this.tableName = tableName;
	}
	/**
	 * for query expression where name may not be told
	 */
	public Schema(){}
	
	public String getName() { return tableName; }

	public boolean hasField(String fieldName) {
		return (fieldTable.get(fieldName) == null);
	}

	public Field getField(String fieldName) {
		return fieldTable.get(fieldName);
	}

	public boolean isAutoIncre(String fieldName) {
		return getField(fieldName).isAutoIncrement();
	}

	public List<String> getFields() {
		return fields;
//		return new ArrayList<String>(fieldTable.keySet());
	}

	public Type defaultValue(String fieldName) {
		return getField(fieldName).getDefaultValue();
	}

	public void setPrimaryKey(String fieldName) {
		if (!primaryKeys.contains(fieldName))
			primaryKeys.add(fieldName);
	}

	public void addField(String fieldName, int type, boolean nullable,
			Type defaultValue, boolean autoIncrement) {
		int length;
		switch (type) {
		case Constant.BOOL: length = BoolType.length(); break;
		case Constant.DATE: length = DateType.length(); break;
		case Constant.DECIMAL: length = DecimalType.length(); break;
		case Constant.FLOAT: length = FloatType.length(); break;
		case Constant.INT: length = IntType.length(); break;
		case Constant.STRING: length = StringType.length(); break;
		case Constant.TIMESTAMP: length = TimeStampType.length(); break;
		default: return;
		}
		
		Field field = new Field(true, currentLength, length, type,
				autoIncrement, nullable, defaultValue);
		currentLength += length;
		
		fields.add(fieldName);
		fieldTable.put(fieldName, field);
	}

	//for join operation
	public void addAll(Schema sch1) {
		// TODO �Զ���ɷ������

	}
}
